#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
struct kvcmp
{
    bool operator()(const pair<string, int>& kv1, const pair<string, int>& kv2)
    {
        return kv1.second > kv2.second;
    }
};

class Solution
{
public:
    vector<string> topKFrequent(vector<string>& words, int k)
    {
        map<string, int> CountMap;
        for (auto& e : words)
        {
            CountMap[e]++;
        }
        vector<pair<string, int>> an(CountMap.begin(), CountMap.end());
        stable_sort(an.begin(), an.end(), kvcmp());
        vector<string> ans;
        auto it = an.begin();
        while (k--)
        {
            ans.push_back(it->first);
            it++;
        }
        return ans;
    }
};

